package main

import (
	"context"
	"log"
	"net/http"

	"calculator/proto"
	"calculator/proto/protoconnect"

	"connectrpc.com/connect"
	"github.com/rs/cors"
)

type CalculatorServer struct{}

func (s *CalculatorServer) Calculate(
	ctx context.Context,
	req *connect.Request[proto.CalculateRequest],
) (*connect.Response[proto.CalculateResponse], error) {
	a := req.Msg.A
	b := req.Msg.B
	operation := req.Msg.Operation

	var result float64
	switch operation {
	case "+":
		result = a + b
	case "-":
		result = a - b
	case "*":
		result = a * b
	case "/":
		if b == 0 {
			return nil, connect.NewError(connect.CodeInvalidArgument, nil)
		}
		result = a / b
	default:
		return nil, connect.NewError(connect.CodeInvalidArgument, nil)
	}

	return connect.NewResponse(&proto.CalculateResponse{
		Result: result,
	}), nil
}

func main() {
	calculator := &CalculatorServer{}
	mux := http.NewServeMux()
	path, handler := protoconnect.NewCalculatorServiceHandler(calculator)
	mux.Handle(path, handler)

	// 添加 CORS 支持
	corsHandler := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"POST", "OPTIONS"},
		AllowedHeaders: []string{"*"},
	}).Handler(mux)

	log.Println("Server starting on :8080...")
	if err := http.ListenAndServe(":8080", corsHandler); err != nil {
		log.Fatalf("Server failed to start: %v", err)
	}
}
